import base64
import io
import string
import random
from random import randint
from src.common.logger import getLogger
from PIL import Image, ImageDraw, ImageFont

logger = getLogger()

def generate_captcha_image(width=140, height=50, length=4):
    """
    生成带干扰的图片验证码（不保存文件，直接返回二进制流）

    参数:
        width: 图片宽度 (默认 140px)
        height: 图片高度 (默认 50px)
        length: 验证码长度 (默认 4 位)

    返回:
        (bytes, str) -> (图片二进制流, 验证码文本)
    """

    # 生成随机颜色 (RGB)
    def get_random_color():
        return (randint(120, 200), randint(120, 200), randint(120, 200))

    # 创建空白图片
    img = Image.new("RGB", (width, height), (250, 250, 250))  # 背景色
    draw = ImageDraw.Draw(img)

    # 生成验证码文本 (0-9, A-Z, a-z)
    characters = string.ascii_letters + string.digits
    image_text = ''.join(random.choices(characters, k=length))
    logger.info(f"generate_captcha_image image_text: {image_text}")

    # 计算文字宽度和高度，以便居中显示
    font = ImageFont.truetype("arial.ttf", size = 36)
    for i in range(length):
        c = image_text[i]
        textbbox = draw.textbbox((0, 0), c, font=font)
        text_width = textbbox[2] - textbbox[0]  # 宽度
        text_height = textbbox[3] - textbbox[1]  # 高度
        position = ((width - text_width) / 5 + randint(20, 30) * i, (height - text_height) / 5)
        draw.text(position, c, font = font, fill = get_random_color())

    # 添加干扰线（3条）
    for _ in range(3):
        x1 = randint(0, width)
        y1 = randint(0, height)
        x2 = randint(0, width)
        y2 = randint(0, height)
        draw.line((x1, y1, x2, y2), fill = get_random_color())

    # 添加干扰点（16个）
    for _ in range(16):
        x = randint(0, width)
        y = randint(0, height)
        draw.point((x, y), fill = get_random_color())

    # 转为二进制流（关键！避免文件IO）
    buffer = io.BytesIO()
    img.save(buffer, format = "PNG")
    buffer.seek(0)

    # 转换为Base64编码
    image_base64 = base64.b64encode(buffer.getvalue()).decode('ascii')
    return image_base64, image_text
